package com.liveneo.adapter.mobile.service.impl;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.liveneo.adapter.base.entity.PrpmCompany;
import com.liveneo.adapter.base.entity.PrpmLocation;
import com.liveneo.adapter.base.entity.PrpmOperateLog;
import com.liveneo.adapter.base.entity.PrpmUser;
import com.liveneo.adapter.base.mapper.PrpmOperateLogMapper;
import com.liveneo.adapter.mobile.service.OperateLogService;
import com.liveneo.adapter.mobile.util.OperateCode;

@Service
public class OperateLogServiceImpl implements OperateLogService {
    @Autowired
    private PrpmOperateLogMapper operateLogDao;

    @Override
    public void addLogMsg(Object obj, String key) {
        // 获得操作对象的名称
        String name = "";
        if (obj instanceof PrpmCompany) {
            PrpmCompany company = (PrpmCompany) obj;
            name = company.getName();
        } else if (obj instanceof PrpmUser) {
            PrpmUser user = (PrpmUser) obj;
            name = user.getUserName();
        } else if (obj instanceof PrpmLocation) {
            PrpmLocation location = (PrpmLocation) obj;
            name = location.getName();
        } 
//        else if (obj instanceof PrpmCheckUser) {
//            PrpmCheckUser checkUser = (PrpmCheckUser) obj;
//            name = checkUser.getName();
//        }
        PrpmOperateLog log = new PrpmOperateLog();
        HttpServletRequest request = null;
        try {
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            request = attr.getRequest();
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (request != null) {
            HttpSession session = request.getSession();
            PrpmUser user = (PrpmUser) session.getAttribute("user");
            if (user != null) {
                log.setUserUuid(user.getUserId());
                log.setUserCode(user.getUserCode());
                log.setOperateCode(key);
                log.setOperateTime(new Date());
                log.setRemark(user.getUserName() + OperateCode.getValue(key) + ":" + name);
                operateLogDao.insert(log);
            }
        }
    }
}
